package com.kiln.juxingqs.ui.vm

import android.app.Application
import android.content.Intent
import android.provider.Settings
import android.util.TypedValue
import android.view.Gravity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.global.commlib.BaseApplication
import client.global.commlib.ContextProvider
import client.global.commlib.network.data.JsonResult
import client.global.commlib.toast.toast
import client.global.commlib.utils.SharedUtil
import client.global.commlib.utils.StoreUtil
import com.kiln.juxingqs.api.bean.Auth
import com.kiln.juxingqs.ui.RegisterActivity
import com.kiln.juxingqs.ui.WjmmActivity
import com.kiln.juxingqs.ui.viewmodel.MiddleVm
import com.kiln.juxingqs.api.bean.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Response

class LoginViewModel(app: Application) : MiddleVm(app) {

    val auth = MutableLiveData<JsonResult<UserInfo>>()
    val account = MutableLiveData<String>()
    val password = MutableLiveData<String>()
    val isShowing = MutableLiveData<Boolean>(false)
    val isShowPwd = MutableLiveData<Boolean>(false)
    fun switchIsShowPwd() {
        isShowPwd.value = !isShowPwd.value!!
    }

    val tyType = MutableLiveData<Int>(-1)

    fun clearAccount() {
        account.value = ""
    }

    fun switchTy() {
        if (tyType.value != 1) {
            tyType.value = 1
        } else {
            tyType.value = -11

        }
    }

    /**
     * 登录
     */
    fun login() {
        if (tyType.value != 1) {
            toast("请同意用户协议")
            return
        }
        if (account.value.isNullOrEmpty() || password.value.isNullOrEmpty()) {
            toast("账户和密码不能为空")
            return
        }
        viewModelScope.launch {
            isShowing.value = true
            flow {
                var emm: Response<JsonResult<Auth>>? = null
                emm = server.login(
                    account.value!!, password.value!!, "android",
                    Settings.Secure.getString(
                        ContextProvider.get().activity!!.getContentResolver(),
                        Settings.Secure.ANDROID_ID,
                    ),
                    "${android.os.Build.BRAND + " " + android.os.Build.MODEL}"
                )
                emit(emm)
            }.map {
                var emm: JsonResult<UserInfo>? = JsonResult<UserInfo>().apply {
                    message = it.body()?.message
                }
                it?.body()?.let {
                    if (it.isSuccess) {
                        SharedUtil.save("token", it.data!!.token)
                        val call = server.userinfo().apply {
                            body()?.let {
                                if (it.isSuccess) {
                                    StoreUtil.saveBean(getApplication(), it.data as UserInfo)
                                    SharedUtil.save("userState", it.data!!.status)
                                }
                            }
                        }.body()
                        emm = call
                        if (call != null && call.isSuccess) {
                            StoreUtil.saveBean(getApplication(), call.data as UserInfo)
                            SharedUtil.save("userState", call.data!!.status)
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
                    toast(cause.message)
                }
            }.collectLatest {
                auth.value = it
            }
        }

    }


    fun goRegister() {
        ContextProvider.get().activity?.apply {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }

    fun goForgetPwd() {
        ContextProvider.get().activity?.apply {
            startActivity(Intent(this, WjmmActivity::class.java))
        }
    }


}